<template>
  <view :data-theme="globPrimary">
    <u-navbar title="收货地址" :custom-back="onBack"></u-navbar>
    <view class="address-wrap">
      <u-form :model="form" ref="uForm" label-width="160rpx" :error-type="['message']">
        <u-form-item label="收货人" prop="consignee">
          <u-input v-model="form.consignee" placeholder="请填写收货人姓名" input-align="right" />
        </u-form-item>
        <u-form-item label="手机号码" prop="phone">
          <u-input
            v-model="form.phone"
            type="number"
            placeholder="请填写收货人手机号"
            input-align="right"
          />
        </u-form-item>
        <u-form-item label="地址">
          <view class="address" @click="showRegionPicker">
            <text class="text">{{ form.areatext }}</text>
            <u-icon name="arrow-right" color="#DCDFE6" size="28"></u-icon>
          </view>
        </u-form-item>
        <u-form-item label="详细地址" prop="address">
          <u-input
            v-model="form.address"
            type="textarea"
            :maxlength="100"
            placeholder="请输入详细地址"
          />
        </u-form-item>
      </u-form>
    </view>
    <view class="address-default">
      <u-checkbox
        v-model="switchVal"
        shape="circle"
        :active-color="globPrimaryColor"
        @change="switchChange"
        >设为默认地址</u-checkbox
      >
    </view>
    <view class="address-bottom-placeholder safe-area-inset-bottom"></view>
    <view class="address-bottom u-flex safe-area-inset-bottom">
      <edu-button class="btn" type="primary" shape="circle" size="medium" @click="onSubmit"
        >保存</edu-button
      >
    </view>
    <region
      ref="picker"
      title="地区选择"
      v-model="show"
      :area-code="areaCode"
      @confirm="onConfirm"
    ></region>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'
import region from './components/region.vue'
export default {
  components: {
    region,
  },
  data() {
    return {
      show: false,
      switchVal: false,
      areaCode: [],
      form: {
        consignee: '',
        phone: '',
        areacode: '',
        areatext: '',
        address: '',
        default: 0,
      },
      rules: {
        consignee: [
          {
            required: true,
            min: 1,
            message: '请填写正确收货人姓名',
            trigger: ['blur'],
          },
        ],
        phone: [
          {
            required: true,
            message: '请输入手机号',
            trigger: ['blur'],
          },
          {
            validator: (rule, value, callback) => {
              return this.$u.test.mobile(value)
            },
            message: '手机号码不正确',
            trigger: ['blur'],
          },
        ],
        address: [
          {
            required: true,
            min: 1,
            message: '请输入详细地址',
            trigger: ['blur'],
          },
        ],
      },
      options: {},
    }
  },
  computed: {
    ...mapGetters({
      globPrimary: 'designSetting/getGlobTheme',
      globPrimaryColor: 'designSetting/getGlobThemeColor',
    }),
  },
  options: { styleIsolation: 'shared' },
  // 监听页面返回
  onBackPress(options) {
    if (options.from === 'navigateBack') {
      return false
    }
    this.onBack()
    return true
  },
  onLoad(options) {
    this.options = options
    if (!this.$u.test.empty(this.options)) {
      this.getAddressInfo()
    }
  },
  methods: {
    getAddressInfo() {
      let val = JSON.parse(this.options.address)
      this.form.consignee = val.consignee
      this.form.phone = val.phone
      this.form.areacode = val.areacode.toString()
      this.form.areatext = val.areatext
      this.form.address = val.address
      this.form.default = val.default
      this.areaCode = val.areacode
      this.switchVal = val.default == 1 ? true : false
    },
    showRegionPicker() {
      this.show = true
    },
    onSubmit() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          if (this.$u.test.empty(this.form.areacode)) {
            this.$u.toast('请选择地区')
            return
          }
          if (!this.$u.test.empty(this.options)) {
            let address = JSON.parse(this.options.address)
            // 修改地址
            this.$edu.api
              .putMallAddressUpdate({
                id: address.id,
                ...this.form,
              })
              .then((res) => {
                this.$u.toast(res.msg)
                // 修改地址时更新修改的地址到订单页面
                if (address.id == this.options.id) {
                  let params = {
                    ...this.form,
                    id: this.options.id,
                  }
                  uni.$emit('chooseAddress', JSON.stringify(params))
                }
                setTimeout(() => {
                  this.onBack()
                }, 200)
              })
              .catch((err) => {
                this.$u.toast(err.msg)
              })
          } else {
            // 添加地址
            this.$edu.api
              .postMallAddressAdd(this.form)
              .then((res) => {
                this.$u.toast(res.msg)
                setTimeout(() => {
                  this.onBack()
                }, 200)
              })
              .catch((err) => {
                this.$u.toast(err.msg)
              })
          }
        }
      })
    },
    onConfirm(title, data) {
      this.form.areacode = data.toString()
      this.form.areatext = title.join(' ')
    },
    switchChange(e) {
      this.form.default = e.value ? 1 : 0
    },
    // 返回上一页
    onBack() {
      let pages = getCurrentPages()
      let page = pages[pages.length - 2]
      if (this.$u.test.empty(page)) {
        this.$u.route({ type: 'switchTab', url: 'pages/user/index' })
      } else {
        this.$u.route({ type: 'back' })
      }
    },
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules)
  },
}
</script>

<style lang="scss" scoped>
::v-deep .address-wrap {
  background-color: #ffffff;
  padding-left: 30rpx;
  .u-form-item {
    padding-right: 30rpx;
  }
  .address {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    .text {
      font-size: 28rpx;
      color: $edu-content-color;
      margin-right: 10rpx;
    }
  }
}
.address-default {
  height: 120rpx;
  padding: 0 30rpx;
  margin-top: 20rpx;
  background: #ffffff;
  display: flex;
  align-items: center;
}
.address-bottom-placeholder {
  width: 100%;
  height: 98rpx;
  box-sizing: content-box;
}
.address-bottom {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 98rpx;
  padding-left: 55rpx;
  padding-right: 55rpx;
  background-color: #fff;
  box-shadow: 0px 2rpx 14rpx 0px rgba(0, 0, 0, 0.06);
  box-sizing: content-box;
  .btn {
    width: 100%;
  }
  ::v-deep .edu-size-medium {
    width: 100%;
  }
}
</style>
